﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace 综合同步
{
    public class ClassByteConvert
    {
        #region Marshal
        public static byte[] Class2CByte<T>(T data)
        {
            int iLenMem = Marshal.SizeOf(data.GetType());
            IntPtr mem = Marshal.AllocHGlobal(iLenMem);
            Marshal.StructureToPtr(data, mem, false);
            byte[] bData = new byte[iLenMem];
            Marshal.Copy(mem, bData, 0, iLenMem);
            Marshal.FreeHGlobal(mem);
            return bData;
        }
        public static T CByte2Class<T>(byte[] data)
        {
            int len = Marshal.SizeOf(typeof(T));
            if (data.Length < len) return default(T);
            IntPtr mem = Marshal.AllocHGlobal(len);
            Marshal.Copy(data.Take(len).ToArray(), 0, mem, len);
            T stData = (T)Marshal.PtrToStructure(mem, typeof(T));
            Marshal.FreeHGlobal(mem);
            return stData;
        }
        #endregion

        #region 串行化
        public static T Byte2Class<T>(byte[] data)
        {
            int len = Marshal.SizeOf(typeof(T));
            using (MemoryStream ms = new MemoryStream(data,0,len))
            {
                T obj = (T)new BinaryFormatter().Deserialize(ms);
                return obj;
            }
        }
        public static byte[] Class2Byte<T>(T data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                new BinaryFormatter().Serialize(ms, data);
                byte[] bData = ms.GetBuffer();
                return bData;
            }
        }
        #endregion
    }
}
